/*
 * FeedDownloader.java
 *
 * Created on July 28, 2007, 11:34 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.afaker.rss.feed.biz;

import com.afaker.rss.search.Indexer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author bruce
 */
public class FeedDownloader {
    private InputStream input;
    private Indexer indexer;
    /** Creates a new instance of FeedDownloader */
    public FeedDownloader(InputStream input) {
        this.input=input;
    }
    /**
     * Download the xml file to local disk as cache.
     * @param localFilePath Where the xml file is stored.
     */
    public void download(String localFilePath)  {
        FileOutputStream output = null;
        if(input==null)
            return ;
        try {
            output = new FileOutputStream(localFilePath);
            int b;
            try {
                while((b = input.read()) != -1) {
                    output.write(b);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            try {
                output.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println("Download successfully."); 
            //After the download completed,index it.
            indexer = new Indexer();
            indexer.index(localFilePath); 
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        try {
            input.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            output.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
    }    
}
